import { auth } from '@clerk/nextjs/server';
import { Metadata } from 'next';
import { notFound } from 'next/navigation';

import { Clip } from '@/state/clipStore';
import { extractClipMetadata } from '@/utils/embeds';

import RadioPageClient from './RadioPageClient';

type Props = {
  params: Promise<{ slug: string }>;
};

async function getData(id: string) {
  const { getToken } = await auth();
  let accessToken;
  try {
    accessToken = await getToken();
  } catch (e) {
    console.log(e);
  }

  const res = await fetch(`${process.env.API_BASE}/api/clip/${id}`, {
    cache: 'no-store',
    headers: {
      ...(accessToken ? { Authorization: `Bearer ${accessToken}` } : {}),
    },
  });

  if (!res.ok) {
    throw new Error('Failed to fetch data');
  }

  return res.json();
}

export async function generateMetadata(props: Props): Promise<Metadata | null> {
  const params = await props.params;
  let product;
  try {
    product = (await getData(params.slug)) as Clip;
  } catch (e) {
    return null;
  }

  if (!product) return null;

  return extractClipMetadata(product);
}

export default async function RadioPageDefine(props: Props) {
  const params = await props.params;
  let data;
  try {
    data = await getData(params.slug);
    console.log(data);
  } catch (e) {
    console.log(e);
    notFound();
  }

  return <RadioPageClient clip={data} />;
}
